package com.example.myxm.activity;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.core.content.ContextCompat;

import com.example.myxm.App;
import com.example.myxm.R;
import com.example.myxm.auth.LoginManager;
import com.example.myxm.databinding.ActivityDataAnalyseBinding;
import com.example.myxm.module.ExpenseBean;
import com.example.myxm.module.IncomeBean;
import com.example.myxm.module.ResultBean;
import com.example.myxm.view.DateMarkerView;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

public class DataAnalyseActivity extends BaseActivity<ActivityDataAnalyseBinding> {

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private List<String> fullDates;
    private List<String> shortDates;

    @NonNull
    @Override
    protected ActivityDataAnalyseBinding getViewBinding(@NonNull LayoutInflater inflater) {
        return ActivityDataAnalyseBinding.inflate(inflater);
    }

    @Override
    protected void initData() {
        setSupportActionBar(getBinding().toolbar);
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setDisplayHomeAsUpEnabled(true);
            bar.setTitle("数据分析");
        }
        getBinding().toolbar.setNavigationOnClickListener(v -> finish());

        loadAndDrawChart();
    }

    private void loadAndDrawChart() {
        int userId = LoginManager.getCurrentUserId(this);
        if (userId < 0) {
            showToast("用户 ID 无效");
            return;
        }


        ResultBean<List<IncomeBean>> incomeRes = App.getDbHelperStatic().getIncomesByUserBean(userId);
        ResultBean<List<ExpenseBean>> expenseRes = App.getDbHelperStatic().getExpensesByUserBean(userId);

        if (incomeRes.getCode() != 200 || expenseRes.getCode() != 200) {
            showToast("数据查询失败");
            return;
        }

        getBinding().tvTotalExpense.setText(String.format(Locale.getDefault(), "总支出：%.2f 元", expenseRes.getData().stream().mapToDouble(ExpenseBean::getAmount).sum()));
        getBinding().tvTotalIncome.setText(String.format(Locale.getDefault(), "总收入：%.2f 元", incomeRes.getData().stream().mapToDouble(IncomeBean::getAmount).sum()));
        List<IncomeBean> incomes   = incomeRes.getData();
        List<ExpenseBean> expenses = expenseRes.getData();

        Comparator<String> cmp = Comparator.comparing(date -> {
            try { return sdf.parse(date); }
            catch (Exception e) { return null; }
        });
        incomes.sort(Comparator.comparing(IncomeBean::getDate, cmp));
        expenses.sort(Comparator.comparing(ExpenseBean::getDate, cmp));

        fullDates  = new ArrayList<>();
        shortDates = new ArrayList<>();
        List<BarEntry> inEntries = new ArrayList<>();
        List<BarEntry> exEntries = new ArrayList<>();
        final int MAX_LABEL = 6;
        final int MAX_LEN   = 5;

        int count = Math.max(incomes.size(), expenses.size());
        for (int i = 0; i < count; i++) {
            String date = "";
            if (i < incomes.size())       date = incomes.get(i).getDate();
            else if (i < expenses.size()) date = expenses.get(i).getDate();

            fullDates.add(date);
            String mmdd = date.length() >= 10 ? date.substring(5, 10) : date;
            if (mmdd.length() > MAX_LEN) {
                mmdd = mmdd.substring(0, MAX_LEN - 1) + "…";
            }
            shortDates.add(mmdd);

            // 金额
            float inAmt = i < incomes.size()   ? (float) incomes.get(i).getAmount()   : 0f;
            float exAmt = i < expenses.size()  ? (float) expenses.get(i).getAmount()  : 0f;
            inEntries.add(new BarEntry(i, inAmt));
            exEntries.add(new BarEntry(i, exAmt));
        }


        BarDataSet dsIn = new BarDataSet(inEntries, "收入");
        dsIn.setColor(ContextCompat.getColor(this, R.color.green_500));
        dsIn.setDrawValues(true);
        dsIn.setValueTextSize(10f);
        dsIn.setValueTextColor(ContextCompat.getColor(this, R.color.green_700));

        BarDataSet dsEx = new BarDataSet(exEntries, "支出");
        dsEx.setColor(ContextCompat.getColor(this, R.color.red_500));
        dsEx.setDrawValues(true);
        dsEx.setValueTextSize(10f);
        dsEx.setValueTextColor(ContextCompat.getColor(this, R.color.red_700));

        float groupSpace = 0.2f, barSpace = 0.05f;
        float barWidth   = (1f - groupSpace) / 2f - barSpace;
        BarData barData  = new BarData(dsIn, dsEx);
        barData.setBarWidth(barWidth);


        getBinding().barChart.setData(barData);
        getBinding().barChart.groupBars(0f, groupSpace, barSpace);

        XAxis xAxis = getBinding().barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setCenterAxisLabels(true);               // 关键：刻度标签居中于组
        float start = 0f;
        float end   = barData.getGroupWidth(groupSpace, barSpace) * count;
        xAxis.setAxisMinimum(start);
        xAxis.setAxisMaximum(end);

        xAxis.setLabelCount(MAX_LABEL, true);
        int step = (int) Math.ceil((float) count / MAX_LABEL);
        xAxis.setGranularity(step);
        xAxis.setValueFormatter(new IndexAxisValueFormatter(shortDates));
        xAxis.setLabelRotationAngle(-30f);
        xAxis.setTextSize(10f);
        xAxis.setAvoidFirstLastClipping(true);

        getBinding().barChart.setDrawGridBackground(false);
        getBinding().barChart.getAxisLeft().enableGridDashedLine(10f, 10f, 0f);
        getBinding().barChart.getAxisRight().setEnabled(false);

        // MarkerView 显示完整日期
        DateMarkerView mv = new DateMarkerView(this, R.layout.view_marker_date, fullDates);
        mv.setChartView(getBinding().barChart);
        getBinding().barChart.setMarker(mv);

        // 交互 & 动画 & 图例
        getBinding().barChart.getDescription().setEnabled(false);
        getBinding().barChart.setTouchEnabled(true);
        getBinding().barChart.setDragEnabled(true);
        getBinding().barChart.setScaleEnabled(true);
        getBinding().barChart.setPinchZoom(true);

        Legend legend = getBinding().barChart.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);

        getBinding().barChart.animateY(800);
        getBinding().barChart.invalidate();
    }


    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}
